/*
    Space Simulation - Simulate the solar system
    Copyright (C) 2010  Guillaume Andrieu and Sylvain Martin

    This file is part of Space Simulation.

    Space Simulation is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Space Simulation is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Space Simulation.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "CSV.h"
#include "Particule.h"

int
explode(char * instr, char ** cmd, char * delim)
{
  int x = 0;
  do
  {
    cmd[x] = instr;
    
    strsep(&instr, delim);
    x++;
  } 
  while(instr != NULL);
  
  cmd[x] = NULL;

  return x;
}

/*
 * read_csv()
 *
 * Lis une ligne au format CSV et cree un tableau
 */
int read_csv(char * str, char ** result)
{
  return explode(str, result, ",");
}

/*
 * make_particule_from_csv()
 *
 * Construit une particule depuis une chaine de caractere 'line'
 * contenant les informations au format CSV (comma-separated values)
 * 
 * error vaut -1 si la chaine de caractere ne contiens pas assez d'informations
 * ou si la particule ne possede pas le nom requis
 *
 * Si 'objectname' vaut NULL, le nom n'est pas verifie
 * sinon, la fonction verifie le nom et retourne une erreur le cas echant.
 */
Particule make_particule_from_csv(char * line, int * error, char * objectname)
{
  char * result[10];
  Particule object;
  
  if(read_csv(line, result) >= 9 && (objectname == NULL || strcmp(result[0], objectname) == 0))
  {
    object = MakeParticule (result[0], MakeVector3D(atof(result[3]),atof(result[4]),atof(result[5])), MakeVector3D(atof(result[6]),atof(result[7]),atof(result[8])), atof(result[1]), atof(result[2]));
    *error = 0;
  }
  else
  {
    *error = 1;
  }

  return object;
}

/*
 * make_particule_from_csv_file()
 *
 * Cherche dans le fichier 'filaname' un objet avec le nom 'objetname'
 * et retourne la particule correspondante
 *
 * Si le fichier ou l'objet est introuvable, error contiens -1
 */
Particule make_particule_from_csv_file(char * objectname, char * filename, int * error)
{
  FILE * fd = fopen(filename, "r");
  char line[1024];
  Particule object;
  int err;

  *error = -1;
  
  if(fd == NULL)
    return object;
  
  while( fscanf(fd, "%s", line) != EOF )
  {
    object = make_particule_from_csv(line, &err, objectname);
    if(err == 0)
    {
      *error = 0;
      break;
    }
  }

  fclose(fd);
  return object;
}
